package com.young.shop.api.service.impl;

import com.young.shop.api.dao.GoodsDaoMapper;
import com.young.shop.api.service.GoodsService;
import com.young.shop.pojo.entity.Goods;
import com.young.shop.pojo.qo.ViewsQO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class GoodsServiceimpl implements GoodsService {

    @Autowired
    private GoodsDaoMapper goodsDaoMapper;


    @Override
    public List<Goods> getAllGoods() {
        List<Goods> goodsList = goodsDaoMapper.selectGoodsAll();
        if (goodsList.size()==0){
            throw new RuntimeException("获取所有商品失败, 数据量为 0 ");
        }
        return goodsList;
    }

    @Override
    public List<Goods> queryGoodsByName(String name) {
        List<Goods> goodsList = goodsDaoMapper.selectGoodsByName(name);
        if (goodsList.size()==0){
            throw new RuntimeException("查询不到这个关键字的商品, 数据量为 0 ");
        }
        return goodsList;
    }

    @Override
    public Goods getGoodsById(String id) {
        Goods goods = goodsDaoMapper.selectGoodsById(id);
        if (goods==null){
            throw new RuntimeException("没有这个商品");
        }

        //浏览量统计
        //获取当日时间
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateNowStr = sdf.format(d);
        System.out.println(dateNowStr);
        //查询当日是否有统计
        ViewsQO viewsQO = goodsDaoMapper.selectGoodsViews(dateNowStr);
        System.out.println(viewsQO);
        System.out.println("1111111111111111");
        if (viewsQO!=null){
            System.out.println("date不为空");
            //如果有数据则找出之前的统计，并更新
            Integer goodsViews = viewsQO.getGoodsViews();
            goodsViews+=1;
            goodsDaoMapper.updateGoodsViews(dateNowStr,goodsViews);
        }else {
            System.out.println("进入新增");
            goodsDaoMapper.insertGoodsViews(dateNowStr);
        }


        return goods;
    }
}
